import tkinter as tk
from pathlib import Path
from tkinter import filedialog, ttk

import win32api
import win32print

from Common.CommonUtils import CommonUtils


class PrintPage(tk.Frame):
    """打印页面"""

    def __init__(self, master):
        super().__init__(master)
        self.master = master
        # 设置页面大小
        # self.config(width=931, height=361)
        self.render()
        # 存储选定的文件夹路径
        self.folder_path = ""

        # 批量打印文件的路径
        self.file_paths = []

        self.printers = None

        self.default_printer = None

        # 添加一个定时器，每秒更新一次队列
        self.after(1000, self.queue_log)

    def render(self):

        self.start_page_label = tk.Label(self, text="打印机：")
        self.start_page_label.grid(row=0, column=0, pady=0, padx=0)

        # 刷新打印机
        self.print_button = CommonUtils.styled_button(self, text="刷新打印机", command=self.refresh, width=20)
        self.print_button.grid(row=0, column=1, pady=0, padx=0)

        # 打印列表下拉框
        self.printers, self.default_printer = self.get_connected_printers()
        self.printer_combobox = ttk.Combobox(self, values=self.printers, width=30)
        self.printer_combobox.current(self.printers.index(self.default_printer))  # 设置默认选中为默认打印机
        self.printer_combobox.bind("<<ComboboxSelected>>", self.on_select_printer)
        self.printer_combobox.grid(row=1, column=0, pady=5, padx=5, columnspan=2)

        # 创建一个显示文件路径的文本框
        self.file_paths_textbox = tk.Text(self, width=60, height=10, wrap="word", font=("Arial", 12))
        self.file_paths_textbox.grid(row=0, column=2, rowspan=8, pady=10, padx=10)
        scrollbar = tk.Scrollbar(self, command=self.file_paths_textbox.yview)
        scrollbar.grid(row=0, column=3, rowspan=6, sticky='ns')
        self.file_paths_textbox['yscrollcommand'] = scrollbar.set

        self.print_button = CommonUtils.styled_button(self, text="批量打印", command=self.print_file, width=20)
        self.print_button.grid(row=2, column=1, pady=10, padx=10)

        # 创建一个选择文件夹的按钮
        self.choose_folder_button = CommonUtils.styled_button(self, text="选择文件夹", command=self.open_folder_dialog,
                                                              width=20)
        self.choose_folder_button.grid(row=2, column=0, pady=20)

        # 打印队列标签
        self.print_queue_label = tk.Label(self, text="打印队列：")
        self.print_queue_label.grid(row=10, column=0)


        # 打印队列文本框
        self.print_queue_textbox = tk.Text(self, width=90, height=10, wrap="word", font=("Arial", 12))
        self.print_queue_textbox.grid(row=11, column=0,columnspan=15, pady=10, padx=10)
        scrollbar1 = tk.Scrollbar(self, command=self.print_queue_textbox.yview)
        scrollbar1.grid(row=11, column=13,columnspan=2, sticky='ns')
        self.print_queue_textbox['yscrollcommand'] = scrollbar1.set


    def open_folder_dialog(self):
        folder_path = filedialog.askdirectory()
        self.folder_path = folder_path
        self.show_file_paths()

    def show_file_paths(self):
        if self.folder_path:
            self.print_button.config(state="normal")  # 启用打印按钮
            folder_path_obj = Path(self.folder_path)
            file_paths = self.get_all_file_paths(folder_path_obj)
            self.file_paths_textbox.delete("1.0", "end")
            for path in file_paths:
                self.file_paths_textbox.insert("end", f"{path}\n")
        else:
            self.file_paths_textbox.delete("1.0", "end")
            self.file_paths_textbox.insert("end", "请先选择一个文件夹")

    def get_all_file_paths(self, directory: Path):
        file_paths = []
        for child in directory.iterdir():
            if child.is_file():
                file_paths.append(str(child))
            elif child.is_dir():
                file_paths.extend(self.get_all_file_paths(child))
        self.file_paths = file_paths
        return file_paths

    # 打印方法
    def print_file(self):
        selected_printer = self.printer_combobox.get()  # 获取选中的打印机
        if self.file_paths:
            for file_path in self.file_paths:
                try:
                # 打开文件并发送到选中的打印机
                    devmode = None
                    if selected_printer == "导出为WPS PDF":
                        tk.messagebox.showerror("警告", "请选择能够打印的设备")
                        return
                    if selected_printer :
                        hprinter = win32print.OpenPrinter(selected_printer)
                        devmode = win32print.GetPrinter(hprinter, 2)["pDevMode"]
                        win32print.ClosePrinter(hprinter)
                    command = f"/d \"{selected_printer}\" /p"
                    win32api.ShellExecute(0, "print", file_path, command, ".", 0)
                    CommonUtils.set_print_queue(f"{file_path}打印成功")
                except Exception as e:
                    tk.messagebox.showerror("错误", f"打印过程中发生错误：{str(e)}")


        else:
            tk.messagebox.showerror("错误", "请先选择一个文件")

    def on_select_printer(self, event):
        selected_printer = self.printer_combobox.get()
        print(f"Selected Printer: {selected_printer}")

    def get_connected_printers(self):
        printers = []
        default_printer = win32print.GetDefaultPrinter()
        flags = win32print.PRINTER_ENUM_LOCAL | win32print.PRINTER_ENUM_CONNECTIONS
        for printer in win32print.EnumPrinters(flags):
            printers.append(printer[2])
        return printers, default_printer

    def refresh(self):
        self.printers, self.default_printer = self.get_connected_printers()
        self.printer_combobox.current(self.printers.index(self.default_printer))  # 设置默认选中为默认打印机
        self.printer_combobox.bind("<<ComboboxSelected>>", self.on_select_printer)

    def queue_log(self):
        # 清空文本框内容 插入尾部
        self.print_queue_textbox.delete('1.0', 'end')
        Information = CommonUtils.get_print_queue()
        for log_content in Information:
            self.print_queue_textbox.insert('end', log_content + "\n")
        self.print_queue_textbox.see('end')

        self.after(1000, self.queue_log)
